<?php

namespace app\admin\model\xiluedu;

use app\common\library\Auth;
use app\common\model\User;
use think\Model;


class UserCoupon extends Model
{

    

    

    // 表名
    protected $name = 'xiluedu_user_coupon';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        //'start_time_text',
        //'end_time_text',
        'use_status_text'
    ];
    


    public function getUseStatusList()
    {
        return ['0' => __('未使用'), '1' => __('已使用')];
    }

    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }

    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }


    public function getUseStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['use_status']) ? $data['use_status'] : '');
        $list = $this->getUseStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function couponGoods(){
        return $this->hasMany("CouponGoods",'coupon_id','coupon_id');
    }
    public function user(){
        return $this->belongsTo(User::class,'user_id','id',[],'left')->setEagerlyType(0);
    }

    public function coupon(){
        return $this->belongsTo("Coupon",'coupon_id','id');
    }

    /**
     * 根据条件获取已领取数量
     */
    public static function get_coupon_count($where){
        return self::where($where)->count();
    }


    /**
     * 获取
     */
    public static function user_pop_coupon($params){
        $auth = Auth::instance();
        $user_id = $auth->id;
        $pagesize = $params['pagesize'] ?? 3;
        $where['end_time'] = ['gt',time()];
        $where['pop_status'] = "1";
        return static::with(['coupon'])
            ->where('user_id',$user_id)
            ->where($where)
            ->limit($pagesize)
            ->select();
    }

    /**
     * 获取用户优惠券
     */
    public static function get_user_coupon($params){
        $auth = Auth::instance();
        $user_id = $auth->id;
        $tab = $params['tab'] ?? 'unuse';
        $pagesize = $params['pagesize'] ?? 10;
        switch($tab){
            case 'used':
                #已使用
                $where['use_status'] = '1';
                $order = 'usetime desc';
                break;
            case "expire":
                #过期
                $where['use_status'] = '0';
                $where['end_time'] = ['lt',time()];
                $order = 'createtime desc';
                break;
            default:
                $where['use_status'] = '0';
                //$where['start_time'] = ['lt',time()];
                $where['end_time'] = ['gt',time()];
                $order = 'end_time asc';
        }

        return static::with(['coupon'])
            ->where('user_id',$user_id)
            ->where($where)
            ->order($order)
            ->paginate($pagesize);
    }


    /**
     * 根据商品id获取优惠券
     */
    public static function get_by_goods_ids($goods_ids){
        $user_id = (Auth::instance())->id;
        $sub = Coupon::alias('coupon')
            ->field("coupon.*")
            ->join("XilushopCouponGoods coupon_goods",'coupon_goods.coupon_id=coupon.id','LEFT')
            ->where('coupon.status','1')
            ->where(function ($query) use($goods_ids){
                $query->where('coupon.range_status','1')
                    ->whereOr("coupon.range_status = 2 AND coupon_goods.goods_id IN (".implode(',',$goods_ids).")");
            })
            ->where('coupon.use_start_time','<',time())
            ->where('coupon.use_end_time','gt',time())
            ->group('coupon_goods.id')
            ->buildSql();
        $lists = static::alias("user_coupon")
            ->field("sub.id,sub.name,sub.type,sub.discount,sub.at_least,sub.money,sub.range_status,user_coupon.id user_coupon_id,user_coupon.coupon_id,user_coupon.use_status")
            ->with(['couponGoods'])
            ->join($sub.' sub','sub.id=user_coupon.coupon_id')
            ->where('user_coupon.id',$user_id)
            ->where('use_status','0')
            ->order('sub.money','desc')
            ->select();
        return $lists;

    }

}
